<template>
<div>
      <div style="width: 500px;height: 300px; border: 1px solid red;" v-html="message">

      </div>
       <select v-model="user.sessionId">
         <template v-for="x in list">
           <option :value="x.sessionId">{{x.name}}</option>
         </template>

       </select>
      <input type="text" v-model="user.info" />
      <button type="button" @click="send(0)">群聊</button>
       <button type="button" @click="send(1)">私聊</button>


</div>

</template>

<script>
  export default {
        name:"testWs",
        data(){
            return{
                ws:"",//websokcet对象
                message:"",
                user:{
                    sessionId:"",//私聊Id
                    info:"",//消息
                    state:0,//0代表群聊，1代表私聊
                    name:""//线上用户名

                },
                list:[]

            }
        },
        methods:{
            createWs(){//创建websokcet对象
              var self = this;
              this.ws = new WebSocket("ws://localhost:8080/helloWs");
              //打开事件
              this.ws.onopen=function(){
                 console.log("客户端打开");
                  //设置状态码为2
                  self.user.state=2;
                 //发送用户名给服务端

                 self.ws.send(JSON.stringify(self.user));

              }
              //关闭事件
              this.ws.onclose=function(){
                 console.log("客户端关闭");
              }
              //接受服务端发送的消息
              this.ws.onmessage=function(msg){
                 console.log(msg.data);
                 var obj = JSON.parse(msg.data);
                 //判断是发送用户名消息，还是聊天
                 if(obj instanceof Array){
                   if(obj[0].state==2){
                        self.list = obj;
                   }
                 }else{
                     self.message += "<p>"+obj.sessionId+"说:"+obj.info+"</p>";
                 }

              },
              //异常触发的事件
              this.ws.onerror=function(rs){
                console.log("客户端出现异常"+rs);
              }

            },
            send(num){//发送
                if(num==1){
                    this.user.state=1;
                }else{
                  this.user.state=0;
                }
                this.ws.send(JSON.stringify(this.user));
            }
        },
        mounted(){
            this.createWs();
            this.user.name = sessionStorage.getItem("name");
        }

  }

</script>

<style>
</style>
